import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:native_dart_package/loading/loading_util.dart';
import 'package:yt_devops/components/event_bus_util/eventbus_util.dart';
import 'package:yt_devops/components/gaps.dart';
import 'package:yt_devops/components/log_utils.dart';
import 'package:yt_devops/components/yt_text_style.dart';
import 'package:yt_devops/components/my_gesture_detector.dart';
import 'package:yt_devops/pages/site/site_observer_list/views/input_center_dialog.dart';
import 'package:yt_devops/resources/str_res_keys.dart';
import 'package:yt_devops/services/predicates.dart';
import 'package:yt_devops/services/site/site_services.dart';
import 'package:yt_devops/styles/styles.dart';
import 'choose_device_page.dart';
/**
 *
 * @Description TODO
 * @Author liuer
 * @CreateTime 2024年05月17日 13:50
 */
class AddEssUnitWidget extends StatefulWidget {
  final int siteId;
  const AddEssUnitWidget({super.key, required this.siteId});
  @override
  State<AddEssUnitWidget> createState() => _AddEssUnitWidgetState();
}

class _AddEssUnitWidgetState extends State<AddEssUnitWidget> {
  SiteServices siteServices = Get.put(SiteServices());
  List unitList = [];
  List<dynamic> chooseDeviceList = []; //选择的设备的map,
  List<int> chooseDeviceIdsList = []; //选择的设备的id,
  StreamSubscription? saveEssUnitSubscription;
  @override
  initState() {
    super.initState();
    saveEssUnitSubscription =
        EventBusUtil.getInstance().on<SaveEssUnit>().listen((event) {
          saveUnitDeviceList();
        });
    getUnitDeviceList();
  }

  @override
  dispose() {
    super.dispose();
    saveEssUnitSubscription?.cancel();
  }

  getUnitDeviceList() async {
    showLoading();
    var result = await siteServices.getUnitDeviceList({'siteId': widget.siteId},
        onError: (error) {
          dismissLoading();
          return false;
        });
    dismissLoading();
    if (result != null) {
      setState(() {
        unitList = result;

      });
    }
  }

  saveUnitDeviceList() async {

    var postMap = {};
    if(unitList.isNotEmpty){
      List groupsList = [];
      for (var element in unitList) {
        if(element['esDevices']!= null && element['esDevices'] is List && element['esDevices'].isNotEmpty){
          String masterDeviceId = '';//选择的主机设备id
          element['esDevices'].forEach((e) {
            if(e['masterSlaveMode'].toString() == '0'){
              masterDeviceId = e['deviceId'].toString();
            }
          });
          if(masterDeviceId.isEmpty){
            showError('至少有一个主机');
            return;
          }
          var map = {
            'groupId': element['groupId'],
            'groupName': element['groupName'],
            'masterDeviceId':masterDeviceId,
            'deviceIds':
            element['esDevices'].map((e) => e['deviceId']).toList(),
          };
          groupsList.add(map);
        }
      }
      postMap = {'siteId': widget.siteId, "groups": groupsList};
      showLoading();
      var result = await siteServices.saveUnitDeviceList(postMap, onError: (error) {
        dismissLoading();
        return false;
      });
      dismissLoading();
      if (result != null) {
        showSuccessToast(ResKey.mineUserManagerSaveSuccess.tr);
      }
    }else{
      showLoading();
      var result = await siteServices.saveUnitDeviceList(postMap = {'siteId': widget.siteId, "groups": []}, onError: (error) {
        dismissLoading();
        return false;
      });
      dismissLoading();
      if (result != null) {
        showSuccessToast(ResKey.mineUserManagerSaveSuccess.tr);
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.only(left: 16,right: 16),

      child: ListView(
      padding: EdgeInsets.zero,
      children: _addUnits(),
    ),);
  }

  List<Widget> _addUnits() {
    List<Widget> list = [];
    var addWidget = GestureDetector(
        behavior: HitTestBehavior.opaque,
        onTap: () {
          unitList.add({
            "groupName": "${unitList.length}#储能单元",
            "esDevices": [],
          });
          setState(() {});
        },
        child: Container(
          padding: const EdgeInsets.only(top: 14, bottom: 14,),
          color: Colour.white,
          child: Row(
            children: [
              Container(

                padding: EdgeInsets.only(left: 16, right: 2),
                child: Image.asset(
                  'assets/images/site_elec_price_add.png',
                  height: 18,
                  width: 18,
                ),
              ),
              Text(
                ResKey.addEssUnit.tr,
                style: ytTextStyle(
                    fontWeight: FontWeight.normal,
                    color: Colour.white,
                    fontSize: 16),
              ),
            ],
          ),
        ));
    if (unitList.isNotEmpty) {
      for (int i = 0; i < unitList.length; i++) {
        list.add(_noDeviceTopItem(i, unitList[i]));
      }
    }
    list.add(addWidget);
    return list;
  }

  _noDeviceTopItem(int index, Map map) {
    return Container(
      margin: const EdgeInsets.only(top: 10),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(8),
        color: Colors.white,
      ),
      clipBehavior: Clip.hardEdge,
      child: Column(
        children: [
          Container(
            color: Colors.white,
            height: 50,
            child: Column(
              children: [
                Gaps.vGap14,
                Row(
                  children: [
                    GestureDetector(
                        behavior: HitTestBehavior.opaque,
                        onTap: () {
                          unitList.removeAt(index);
                          setState(() {});
                        },
                        child: Container(
                          padding: EdgeInsets.only(left: 16.w, right: 2),
                          child: Image.asset(
                            'assets/images/site_elec_price_delete.png',
                            height: 18,
                            width: 18,
                          ),
                        )),
                    Text(
                      map['groupName'],
                      style: ytTextStyle(
                          fontWeight: FontWeight.w500,
                          color: Colour.mainTextColor,
                          fontSize: 16),
                    ),
                    GestureDetector(
                        onTap: () {
                          _showInputDialog(context,map['groupName'],(value){
                            // Log.d('value==' + value.toString());
                            map['groupName'] = value;
                            setState(() {

                            });
                          });
                        },
                        child: Container(
                          padding: const EdgeInsets.only(left: 8, right: 8),
                          child: Image.asset('assets/images/site_monitor_edit.png'),
                        )),
                    Spacer(),
                    GestureDetector(
                        behavior: HitTestBehavior.opaque,
                        onTap: () {
                          if(map['esDevices'].isNotEmpty){
                            chooseDeviceIdsList.clear();
                            List tempList = map['esDevices'];
                            for (var element in tempList) {
                              if(element['deviceId'] != null && element['deviceId'] is int){
                                chooseDeviceIdsList.add(element['deviceId']);
                              }
                            }
                          }
                          Navigator.push(
                            Get.context!,
                            MaterialPageRoute(
                              builder: (context) =>
                                  ChooseDevicePage(
                                    title: ResKey.selectDevice.tr,
                                    listUrl: '$iot/es/optionalDeviceList',
                                    params: {
                                      'siteId': widget.siteId,
                                      'groupId': map['groupId'],
                                    },
                                    isMultiSelect: true,
                                    selectedIds: chooseDeviceIdsList,
                                    searchPlaceholder:ResKey.plsInput.tr + ResKey.deviceName.tr,
                                    selectedCompleted: (chooseDataList,chooseIdsList){
                                      unitList[index]['esDevices'] = chooseDataList;
                                      chooseDeviceIdsList = chooseIdsList;
                                      setState(() {

                                      });
                                    },
                                  ),
                            ),
                          );
                        },
                        child: Row(
                          children: [
                            Text(
                              ResKey.selectDevice.tr,
                              style: ytTextStyle(
                                  fontWeight: FontWeight.normal,
                                  color: Colour.hintTextColor,
                                  fontSize: 16),
                            ),
                            Image.asset(
                              'assets/images/right_arrow.png',
                              width: 16.w,
                              height: 16.w,
                            ),
                            Gaps.hGap16,
                          ],
                        ))
                  ],
                ),
                Gaps.vGap14,
              ],
            ),
          ),
          Container(
            margin: EdgeInsets.only(left: 16.w, right: 16.w),
            height: 0.5,
            color: Colour.dividerColor,
          ),
          Container(
            color: Colors.white,
            child: Column(
              children: _getDeviceList(map['esDevices']),
            ),
          )
        ],
      ),
    );
  }
  Future<String?> _showInputDialog(BuildContext context,String textString,Function(String?) callBack) async {
    String? inputText = await showDialog(
      context: context,
      builder: (BuildContext context) =>
          InputDialog(title: ResKey.modifyDeviceName.tr,textString:textString,callBack: (String? value){
            callBack(value);
          },),
    );
    return inputText;
  }

  _getDeviceList(List devicesList) {
    List<Widget> list = [];
    Log.d('devicesList==' + devicesList.toString());
    if (devicesList != null && devicesList.isNotEmpty) {
      list.add(Gaps.vGap16);
      for (var element in devicesList) {
        list.add(_deviceItem(element,devicesList));
      }
      list.add(
        Container(
          margin: EdgeInsets.only(left: 16.w, right: 16.w),
          height: 0.5,
          color: Colour.dividerColor,
        ),
      );
    }
    return list;
  }

  _deviceItem(Map map,List devicesList) {
    Log.d('map===' + map.toString());
    return Container(
      margin: EdgeInsets.only(left: 16.w, right: 16.w, bottom: 8),
      color: Colour.white,
      child: Column(
        children: [
          _rowItem('${ResKey.deviceName.tr}：', map['deviceName'] != null ? map['deviceName'].toString() : '--',),
          Gaps.vGap8,
          _rowItem('${ResKey.deviceSn.tr}：', map['sn'] != null ? map['sn'].toString() : '--',),
          Row(children: [
            Container(
              width: 92.w,
              height: 20,
              child: Text(
                '${ResKey.masterSlaveMode.tr}:' ,
                maxLines: 2,
                style: ytTextStyle(
                    fontWeight: FontWeight.normal,
                    color: Colour.lightTextColor,
                    fontSize: 13),
              ),

            ),
            MyGestureDetector(onTap: (){
              _switchMasterSlaveMode(map,'0',devicesList);
            }, child:Container(
              height: 20,
              margin: EdgeInsets.only(top: 8,bottom: 4,right: 4),
              child: Image.asset(
                map['masterSlaveMode'].toString() == '0'
                    ? 'assets/images/site_elec_price_selected.png'
                    : 'assets/images/site_elec_price_unselected.png',
                height: 16,
                width: 16,
              ),
            )),
            Container(
              margin: EdgeInsets.only(top: 8,bottom: 4,right: 12),
              child: Text(ResKey.host.tr,style: ytTextStyle(fontSize: 14),),
            ),
            MyGestureDetector(onTap: (){
              _switchMasterSlaveMode(map,'1',devicesList);
            }, child: Container(
              margin: EdgeInsets.only(top: 8,bottom: 4,right: 4),
              child: Image.asset(
                map['masterSlaveMode'].toString() == '1'
                    ? 'assets/images/site_elec_price_selected.png'
                    : 'assets/images/site_elec_price_unselected.png',
                height: 16,
                width: 16,
              ),
            )),
            Container(
              margin: const EdgeInsets.only(top: 8,bottom: 4,right: 12),
              child: Text(ResKey.slave.tr,style: ytTextStyle(fontSize: 14),),
            ),
          ],),

          Gaps.vGap8
        ],
      ),
    );
  }

  //切换主从模式
  _switchMasterSlaveMode(Map map,String mode,List devicesList){
    if( map['masterSlaveMode'].toString() == '0' && mode == '1'){
      showError('至少有一个主机');
      return;
    }
    for (var element in devicesList) {
      if(element['sn'].toString() == map['sn'].toString()){
        element['masterSlaveMode'] = '0';
      }else{
        element['masterSlaveMode'] = '1';
      }
    }
    setState(() {
    });
  }

  _rowItem(String title,String value ) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Container(
          height: 20,
          width: 92.w,
          child: Text(
            title ,
            maxLines: 2,
            style: ytTextStyle(
                fontWeight: FontWeight.normal,
                color: Colour.lightTextColor,
                fontSize: 13),
          ),
        ),
        Expanded(child: Text(
          value,
          maxLines: 2,
          style: ytTextStyle(
              fontWeight: FontWeight.normal,
              color: Colour.mainTextColor,
              fontSize: 13),
        ),)
      ],
    );
  }
}
